<template>
  <view class="email-modify">
    <view class="input-item">
      <text class="label">新邮箱：</text>
      <input type="email" placeholder="请输入新邮箱" v-model="newEmail" />
    </view>
    <view class="input-item">
      <text class="label">确认新邮箱：</text>
      <input type="email" placeholder="请再次输入新邮箱" v-model="confirmEmail" />
    </view>
    <button @click="modifyEmail" class="submit-button">修改邮箱</button>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { modifyEmailAPI } from "@/api/user"; // 引入修改邮箱的API调用函数

const newEmail = ref("");
const confirmEmail = ref("");

// 修改邮箱逻辑
const modifyEmail = async () => {
  // 检查新邮箱和确认邮箱是否一致
  if (newEmail.value !== confirmEmail.value) {
    uni.showToast({
      title: "新邮箱和确认邮箱不一致",
      icon: "none",
    });
    return;
  }

  // 校验邮箱格式
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(newEmail.value)) {
    uni.showToast({
      title: "请输入有效的邮箱地址",
      icon: "none",
    });
    return;
  }

  try {
    const response = await modifyEmailAPI({ email: newEmail.value });
    if (response.success) {
      uni.showToast({
        title: "邮箱修改成功",
      });
    } else {
      uni.showToast({
        title: "邮箱修改失败：" + response.message,
        icon: "none",
      });
    }
  } catch (error) {
    console.error("修改邮箱失败:", error);
    uni.showToast({
      title: "修改邮箱异常",
      icon: "none",
    });
  }
};
</script>

<style scoped>
.email-modify {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.input-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.label {
  width: 80px;
  font-size: 14px;
  color: #333;
  margin-right: 10px;
}

input {
  flex: 1;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

input:focus {
  border-color: #007aff;
}

.submit-button {
  background-color: #007aff;
  color: white;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 16px;
  transition: background-color 0.3s ease;
  border: none;
  outline: none;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #0056b3;
}
</style>
